package utility

import (
	"gin_demo/internal/consts"
	"gin_demo/internal/model"
	"log"
	"os"

	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

func SystemInit() *viper.Viper {
	v := viper.New()
	dir, _ := os.Getwd()
	v.SetConfigFile(dir + "/" + "/manifest/config/config.yaml")
	v.SetConfigType("yaml")
	err := v.ReadInConfig()
	if err != nil {
		log.Println(err)
	}
	err = v.Unmarshal(&consts.App.Configuration)
	if err != nil {
		log.Println(err)
	}

	return v
}

func InitMysql() *gorm.DB {
	db := consts.App.Configuration.Database
	dsn := db.UserName + ":" + db.PassWord + "@tcp(" + db.Address + ":" + db.Port + ")/" + db.DBName + "?charset=utf8mb4&parseTime=True&loc=Local"
	d, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		consts.App.Log.Error(err.Error())
	}
	_ = d.AutoMigrate(&model.Rotation{}, &model.AdminInfo{}, &model.Category{}, &model.Role{}, &model.RolePermissions{}, &model.Permission{}, &model.Order{}, &model.GoodsInfo{}, &model.GoodsOptopmsInfo{})
	return d
}
